package com.tduck.cloud.datav.service.charts;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import com.tduck.cloud.datav.constant.ChartsConstants;
import com.tduck.cloud.datav.request.ChartDataRequest;
import com.tduck.cloud.datav.service.BaseChartDataService;
import com.tduck.cloud.report.data.params.QueryFieldListParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.LinkedMap;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 轮播表
 *
 * @author tduck
 */
@Component
@Slf4j
public class CarouselTableChartDataService extends BaseChartDataService {
    @Override
    public Map<String, Object> getChartData(ChartDataRequest request) {
        QueryFieldListParams queryFieldListParams = new QueryFieldListParams();
        queryFieldListParams.setQueryObjName(request.getIndexName());
        queryFieldListParams.setLimit(request.getLimit());
        queryFieldListParams.setFields(request.getIndex().stream().map(ChartDataRequest.IndexField::getId).collect(Collectors.toList()));
        queryFieldListParams.setFilter(ListUtil.of(request.getFilter()));
        List<LinkedMap> list = dataSearchTemplate.queryFieldList(queryFieldListParams);
        List<List<Object>> dataList = new LinkedList<>();
        List<String> orderByList = request.getIndex().stream().map(ChartDataRequest.IndexField::getId).collect(Collectors.toList());
        for (LinkedMap map : list) {
            LinkedList<Object> row = new LinkedList<Object>();
            for (String key : orderByList) {
                row.add(map.get(key));
            }
            dataList.add(row);
        }
        Map<String, Object> result = MapUtil.of(ChartsConstants.DATA, dataList);
        result.put(ChartsConstants.HEADER, request.getIndex().stream().map(ChartDataRequest.IndexField::getLabel).collect(Collectors.toList()));
        return result;
    }
}
